//
//  HECreateOrderViewController.m
//  HealthElderly
//
//  Created by 吴欧 on 2020/10/27.
//  Copyright © 2020 honglutec. All rights reserved.
//

#import "HECreateOrderViewController.h"
#import "GroupShadowTableView.h"
#import "HEOrderAddressCell.h"
#import "HEOrderGoodsHeadrCell.h"
#import "HEOrderGoodsCell.h"
#import "HEOrderGoodsFooterCell.h"
#import "HEOrderLeaveMsgCell.h"
#import "HEOrderServerTimeCell.h"
#import "HEOrderDispatchCell.h"
#import "HEOrderPayCell.h"
#import "HEOrderAddAddressCell.h"
#import "HEOrderTabBarView.h"
#import "HEPreviewOrderModel.h"
#import "HEPreviewStoreOrderModel.h"
#import "HECreateOrderRequest.h"
#import "HECreateOrderResponse.h"
#import "PreferViewController.h"
#import "HEWxPayReqModel.h"
#import "HEPayResultResViewController.h"
#import "HEPaymentModel.h"
#import "HEOrderDetailsViewController.h"
#import "HEOrderPresByCartResponse.h"
#import "ZFScanViewController.h"
#import "HEAddressViewController.h"
#import "HEQRPayView.h"
#import "HETranspFeesModel.h"
#import "HEDocOrderTransFeesCell.h"

@interface HECreateOrderViewController ()<GroupShadowTableViewDelegate, GroupShadowTableViewDataSource, HEOrderTabBarViewDelegate, HEOrderAddressCellDelegate>

@property (nonatomic, strong) GroupShadowTableView *tableView;
@property (nonatomic, strong) NSMutableArray *sections;

@property (nonatomic, strong) GDFormModel *formModel;
@property (nonatomic, strong) HEPreviewOrderModel *detials;
@property (nonatomic, strong) HEPreviewStoreOrderModel *storeDetials;
@property (nonatomic, strong) NSMutableArray *goodsDataSource;
@property (nonatomic, strong) HEOrderTabBarView *tabbar;
@property (nonatomic, strong) HEWxPayReqModel *wxModel;

// 创建一个全局的group
@property (nonatomic, strong) dispatch_group_t group;
@property (nonatomic, strong) HEOrderModel * order;
@property (nonatomic, strong) HEOrderPresByCartResponse *cartDetails;
@property (nonatomic, strong) HETranspFeesModel *transpFee;
@property (nonatomic, strong) NSString *totalPayAmount;
@property (nonatomic, strong) NSString *goodTotalPrice;

@end

@implementation HECreateOrderViewController

- (HETranspFeesModel *)transpFee {
    if (!_transpFee) {
        _transpFee = [HETranspFeesModel new];
        _transpFee.transFees = [NSDecimalNumber decimalNumberWithString:@"0"];
        _transpFee.distance = [NSDecimalNumber decimalNumberWithString:@"0"];
    }
    return _transpFee;
}

- (GDFormModel *)formModel {
    if (!_formModel) {
        _formModel = [[GDFormModel alloc] init];
        _formModel.proxyVC = self;
    }
    return _formModel;
}

- (NSMutableArray *)goodsDataSource {
    if (!_goodsDataSource) {
        _goodsDataSource = [NSMutableArray array];
    }
    return _goodsDataSource;
}

- (HEOrderPreviewRequest *)previewModel {
    if (!_previewModel) {
        _previewModel = [HEOrderPreviewRequest new];
    }
    return _previewModel;
}

- (HEPreviewOrderModel *)detials {
    if (!_detials) {
        _detials = [HEPreviewOrderModel new];
    }
    return _detials;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:KNotificationPaySuccess object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:KNotificationPayFailure object:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"创建订单";

    [self initUI];
    [self initTabbar];
 
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(paySuccess) name:KNotificationPaySuccess object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(payFialure) name:KNotificationPayFailure object:nil];
    
    [self loadData];
}

- (void)initUI {
    
    CGFloat tabbarHeight = 49 + KSafeTabbarHeight;

    self.tableView = [[GroupShadowTableView alloc] initWithFrame:CGRectMake(0, ZXNavBarHeight, KScreenWidth, KScreenHeight - ZXNavBarHeight - tabbarHeight) style:UITableViewStylePlain];
    self.tableView.groupShadowDelegate = self;
    _tableView.groupShadowDataSource = self;
    _tableView.showSeparator = YES;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.showsVerticalScrollIndicator = NO;
    self.tableView.backgroundColor = CViewBgColor;
    
    UIView *v = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 40)];
    v.backgroundColor = [UIColor clearColor];
    self.tableView.tableFooterView = v;
    [self.view addSubview:_tableView];
}

- (void)initTabbar {
    
    CGFloat tabbarHeight = 49 + KSafeTabbarHeight;

    HEOrderTabBarView *tabbar = [HEOrderTabBarView new];
    tabbar.delegate = self;
    [self.view addSubview:tabbar];
    self.tabbar = tabbar;
    
    [tabbar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.view);
        make.height.mas_offset(tabbarHeight);
    }];
}

#pragma mark - load Data
- (void)loadData {
    __weak typeof(self) weakself = self;

    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(queue, ^{
        weakself.group = dispatch_group_create();
        [weakself loadOrderData];
        [weakself loadPaydata];

        //因上面请求中有加入dispatch_group_enter 和 dispatch_group_leave,所以真正等待上面线程执行完才执行这里面的请求
        dispatch_group_notify(weakself.group, queue, ^{
            dispatch_main_async_safe(^{
                [weakself initCell2];
            })
        });
    });
}

- (void)loadOrderData {
    
    dispatch_group_enter(_group);
    __weak typeof(self) weakself = self;

    NSString *urls = @"";
    if (_previewType == HESubmitPreviewTypeByGoodsDetails) {
        urls = KsubmitPreview;
    }else if (_previewType == HESubmitPreviewTypeByCart) {
        urls = KsubmitStorePreview;
    }
     
    [WOAFNetWorkingHandle GETWithBaseUrl:KServerUrl suffixUrl:urls parameters:_previewModel success:^(id  _Nonnull responseObject) {
        NSLog(@"response：  %@", [responseObject mj_JSONString]);
        HEResponse *response = [HEResponse mj_objectWithKeyValues:responseObject];

        if (self.previewType == HESubmitPreviewTypeByGoodsDetails) {
            self.detials = [HEPreviewOrderModel mj_objectWithKeyValues:response.data];
            self.formModel.order_addres = self.detials.address;
            self.goodTotalPrice = [NSDecimalNumber rounding:self.detials.calcAmount.totalAmount afterPoint:2];
        }else if (self.previewType == HESubmitPreviewTypeByCart) {
            self.cartDetails = [HEOrderPresByCartResponse mj_objectWithKeyValues:response.data];
            self.formModel.order_addres = self.cartDetails.address;
            self.goodTotalPrice = [NSDecimalNumber rounding:self.detials.calcAmount.totalAmount afterPoint:2];
        }
        
        [self loadTranpFeeData];
        dispatch_group_leave(weakself.group);

    } failure:^(NSError * _Nonnull error) {
        dispatch_group_leave(weakself.group);

    }];
}

- (void)loadPaydata {
    dispatch_group_enter(_group);
    __weak typeof(self) weakself = self;

    [WOAFNetWorkingHandle GETWithBaseUrl:KServerUrl suffixUrl:Kpaymentlist parameters:@{@"appSource":@(KAppSource)} success:^(id  _Nonnull responseObject) {
        NSLog(@"response：  %@", [responseObject mj_JSONString]);
        HEArrayResponse *response = [HEArrayResponse mj_objectWithKeyValues:responseObject];
        
        self.formModel.order_payments = [HEPaymentModel mj_objectArrayWithKeyValuesArray:response.data];
        
        if (self.formModel.order_payments.count > 0) {
            HEPaymentModel *firstModel = self.formModel.order_payments.firstObject;
            firstModel.isChoose = YES;
            self.formModel.order_payType = firstModel.code;
        }
        
        dispatch_group_leave(weakself.group);

    } failure:^(NSError * _Nonnull error) {
        dispatch_group_leave(weakself.group);
    }];
}

- (void)loadTranpFeeData {
    dispatch_group_enter(_group);
    __weak typeof(self) weakself = self;
    
    // 非上门
    if (!_goods.visit) {
        [self calcPayPric];
        dispatch_group_leave(weakself.group);
        return;
    }
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setObject: [NSString stringWithFormat:@"%f",self.formModel.order_addres.latitude] forKey:@"lat"];
    [params setObject: [NSString stringWithFormat:@"%f",self.formModel.order_addres.longitude] forKey:@"lng"];
    [params setObject:[NSNumber numberWithLong: _goods.id] forKey:@"productId"];

    [WOAFNetWorkingHandle POSTWithBaseUrlByKeyValue:KServerUrl suffixUrl:KtranspFee parameters:params success:^(id  _Nonnull responseObject) {
        
        HEResponse *response = [HEResponse mj_objectWithKeyValues:responseObject];
        self.transpFee = [HETranspFeesModel mj_objectWithKeyValues:response.data];
        self.formModel.od_transFee = self.transpFee;
        [self calcPayPric];
        dispatch_group_leave(weakself.group);
    } failure:^(NSError * _Nonnull error) {
        [self calcPayPric];
        dispatch_group_leave(weakself.group);
    }];
}

- (void)calcPayPric {
    dispatch_main_async_safe(^{
        // 合计 = 商品总计 + 交通费
        NSDecimalNumber *productTotal = [NSDecimalNumber decimalNumberWithString: self.goodTotalPrice];
        NSDecimalNumber *tot = [productTotal decimalNumberByAdding: self.transpFee.transFees];
        self.totalPayAmount = [tot stringValue];
        self.tabbar.totalPrice = [NSDecimalNumber rounding:self.totalPayAmount afterPoint:2];
        
    //    [self.tableView.fd_keyedHeightCache invalidateAllHeightCache];
        [self.tableView reloadData];
    })
}

#pragma mark -
- (void)initCell2 {
    // 总段
    _sections = [NSMutableArray array];
    [self.goodsDataSource removeAllObjects];
    NSMutableArray *classArr = [NSMutableArray array];
    
    // 添加地址
    GDFiterCellModel *addAddrsModel = [GDFiterCellModel new];
    addAddrsModel.cellKlass = HEOrderAddAddressCell.class;
    addAddrsModel.cellType = GDFiterCellTypeOrderAddAddress;
    addAddrsModel.cellDisplayType = self.formModel.order_addres == nil ? GDCellDisplayShow:GDCellDisplayNone;

    // 地址
    GDFiterCellModel *hasAddresModel = [GDFiterCellModel new];
    hasAddresModel.cellKlass = HEOrderAddressCell.class;
    hasAddresModel.cellType = GDFiterCellTypeOrderHasAddress;
    hasAddresModel.cellDisplayType = self.formModel.order_addres != nil ? GDCellDisplayShow:GDCellDisplayNone;


    // 商品段落header
    GDFiterCellModel *goodheadModel = [GDFiterCellModel new];
    goodheadModel.cellKlass = HEOrderGoodsHeadrCell.class;
    goodheadModel.cellType = GDFiterCellTypeOrderGoodsHead;
    
    // 商品
    GDFiterCellModel *goodsModel = [GDFiterCellModel new];
    goodsModel.cellKlass = HEOrderGoodsCell.class;
    goodsModel.cellType = GDFiterCellTypeOrderGoods;

    // 商品段落footer
    GDFiterCellModel *goodsFooterModel = [GDFiterCellModel new];
    goodsFooterModel.cellKlass = HEOrderGoodsFooterCell.class;
    goodsFooterModel.cellType = GDFiterCellTypeOrderGoodsFooter;
    
    // 交通费用详请
    GDFiterCellModel *transFeeModel = [GDFiterCellModel new];
    transFeeModel.cellKlass = HEDocOrderTransFeesCell.class;
    transFeeModel.cellType = GDFiterCellTypeGoodTransFeesInfo;
    transFeeModel.cellDisplayType = self.goods.visit ? GDCellDisplayShow:GDCellDisplayNone;
        
    // 服务时间
    GDFiterCellModel *serverTimeModel = [GDFiterCellModel new];
    serverTimeModel.cellKlass = HEOrderServerTimeCell.class;
    serverTimeModel.cellType = GDFiterCellTypeOrderServerTime;
    serverTimeModel.cellDisplayType = GDCellDisplayNone;

    // 立即指派
    GDFiterCellModel *dispatchModel = [GDFiterCellModel new];
    dispatchModel.cellKlass = HEOrderDispatchCell.class;
    dispatchModel.cellType = GDFiterCellTypeOrderDispatch;
    dispatchModel.cellDisplayType = GDCellDisplayNone;
    if (self.detials.cartPromotionItemList.count > 0) {
        HECartpromotionItemModel *carItem = self.detials.cartPromotionItemList.firstObject;
        if (carItem.channel == HEChannelTypeSpinalReh) {
            serverTimeModel.cellDisplayType = GDCellDisplayShow;
        }else if (self.goods.visit) {
            serverTimeModel.cellDisplayType = GDCellDisplayShow;
            dispatchModel.cellDisplayType = GDCellDisplayShow;
        }
    }

    // 留言
    GDFiterCellModel *leaveModel = [GDFiterCellModel new];
    leaveModel.cellKlass = HEOrderLeaveMsgCell.class;
    leaveModel.cellType = GDFiterCellTypeOrderLeaveMsg;
    
    // 支付方式
    GDFiterCellModel *payModel = [GDFiterCellModel new];
    payModel.cellKlass = HEOrderPayCell.class;
    payModel.cellType = GDFiterCellTypeOrderPay;
    
    
    // 添加的时候注意顺序，暂未对顺序做处理
    classArr = @[addAddrsModel,hasAddresModel, goodheadModel, goodsModel, goodsFooterModel, transFeeModel, leaveModel,serverTimeModel,dispatchModel, payModel].mutableCopy;
    [self.tableView mc_registerCellByFiterModels:classArr];

    NSInteger i = 0;
    for (GDFiterCellModel *model in classArr) {
         NSMutableArray *secs = [NSMutableArray array];
         
        // 隐藏未达到条件的cell
        if (model.cellDisplayType == GDCellDisplayNone) {
            continue;
        }
        else if (model.cellType == GDFiterCellTypeOrderGoods ||
                 model.cellType == GDFiterCellTypeOrderGoodsFooter ||
                 model.cellType == GDFiterCellTypeOrderServerTime ||
                 model.cellType == GDFiterCellTypeOrderDispatch) { // 所有商品项不加入段落，仅加入如段落 如下
            continue;
        }
        else if (model.cellType == GDFiterCellTypeOrderGoodsHead) {
            
            if (self.previewType == HESubmitPreviewTypeByCart) {
                for (HEPreviewOrderModel *cartHead in self.cartDetails.confirmOrderResultList) {
                    NSMutableArray *cartheadArr = [NSMutableArray array];
                    [cartheadArr addObject:model]; // 添加段头
                    // 添加中间商品
                    for (HECartpromotionItemModel *goodItem in cartHead.cartPromotionItemList) {
                        GDFiterCellModel *good = [GDFiterCellModel new];
                        good.cellKlass = HEOrderGoodsCell.class;
                        good.cellType = GDFiterCellTypeOrderGoods;
                        [cartheadArr addObject:goodsModel];
                    }
                    [cartheadArr addObject:goodsFooterModel]; // 添加段尾
                    [_sections addObject:cartheadArr];
                }
            }else {
                [secs addObject:model]; // 添加段头
                // 添加中间商品
                for (HECartpromotionItemModel *goodItem in self.detials.cartPromotionItemList) {
                  GDFiterCellModel *good = [GDFiterCellModel new];
                  good.cellKlass = HEOrderGoodsCell.class;
                  good.cellType = GDFiterCellTypeOrderGoods;
                  [secs addObject:goodsModel];
                }
                [secs addObject:goodsFooterModel]; // 添加段尾
            }
        }
        else if (model.cellType == GDFiterCellTypeOrderLeaveMsg) {
            if (serverTimeModel.cellDisplayType == GDCellDisplayShow) {
                [secs addObject:serverTimeModel];
            }
            if (dispatchModel.cellDisplayType == GDCellDisplayShow) {
                [secs addObject:dispatchModel];
            }
            [secs addObject:model];
        }
        else if (model.cellType == GDFiterCellTypeOrderPay) {
            
            for (HEPaymentModel *pay in self.formModel.order_payments) {
                GDFiterCellModel *payModel = [GDFiterCellModel new];
                payModel.cellKlass = HEOrderPayCell.class;
                payModel.cellType = GDFiterCellTypeOrderPay;
                [secs addObject:payModel];
            }
        }
        else {
            [secs addObject:model];
        }
         
        if (model.cellType == GDFiterCellTypeOrderGoodsHead && self.previewType == HESubmitPreviewTypeByCart) {
            
        }else {
            [_sections addObject: secs];
        }
        i++;
     }
    
    if (_previewType == HESubmitPreviewTypeByGoodsDetails) {
        NSMutableArray *section1 = [NSMutableArray array];
        HECartpromotionItemModel *good = self.detials.cartPromotionItemList.lastObject;
        NSInteger totalNum = 0;

        [section1 addObject:good.storeName];
        
        for (HECartpromotionItemModel *goodItem in self.detials.cartPromotionItemList) {
            [section1 addObject:goodItem];
            totalNum += goodItem.quantity;
        }
        
        NSString *footerTotalStr = @"";
        if (_goods.visit) {
            NSDecimalNumber *productTotal = [NSDecimalNumber decimalNumberWithString:self.detials.calcAmount.totalAmount];
           
            // 合计 = 商品总计 + 交通费
            NSDecimalNumber *tot = [productTotal decimalNumberByAdding: self.transpFee.transFees];
            
            [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundPlain scale:2 raiseOnExactness:NO raiseOnOverflow:NO raiseOnUnderflow:NO raiseOnDivideByZero:YES];
            
            footerTotalStr = [NSString stringWithFormat:@"交通费￥%@(共%@公里)  合计：￥%@"
                              ,  [_transpFee.transFees keepTwo]
                              , [_transpFee.distance keepTwo]
                              , [NSDecimalNumber rounding:[tot stringValue] afterPoint:2]];
        }else {
            footerTotalStr = [NSString stringWithFormat:@"共%ld件  运费￥%@  合计：￥%@", (long)totalNum,
                              [NSDecimalNumber rounding:self.detials.calcAmount.freightAmount afterPoint:2],
                              [NSDecimalNumber rounding:self.detials.calcAmount.totalAmount afterPoint:2]];
        }
        
        [section1 addObject: footerTotalStr];

        [self.goodsDataSource addObject:section1];
        
        self.formModel.order_goodsDataSource = self.goodsDataSource;
    }else if (_previewType == HESubmitPreviewTypeByCart) {
        for (HEPreviewOrderModel *cartHead in self.cartDetails.confirmOrderResultList) {
            NSMutableArray *section1 = [NSMutableArray array];
            NSInteger totalNum = 0;

            [section1 addObject:cartHead.storeName];
            // 添加中间商品
            for (HECartpromotionItemModel *goodItem in cartHead.cartPromotionItemList) {
                [section1 addObject:goodItem];
                totalNum += goodItem.quantity;
            }
            
            NSString *footerTotalStr = @"";
            if (_goods.visit) {
                //
                NSDecimalNumber *productTotal = [NSDecimalNumber decimalNumberWithString:self.detials.calcAmount.totalAmount];
               
                // 合计 = 商品总计 + 交通费
                NSDecimalNumber *tot = [productTotal decimalNumberByAdding: _transpFee.transFees];
                footerTotalStr = [NSString stringWithFormat:@"交通费￥%@(共%@公里)  合计：￥%@"
                                  , [_transpFee.transFees keepTwo]
                                  ,  [_transpFee.distance keepTwo]
                                  , [NSDecimalNumber rounding:[tot stringValue] afterPoint:2]];
            }else {
                footerTotalStr = [NSString stringWithFormat:@"共%ld件  运费￥%@  合计：￥%@", (long)totalNum,
                                  [NSDecimalNumber rounding:self.detials.calcAmount.freightAmount afterPoint:2],
                                  [NSDecimalNumber rounding:self.detials.calcAmount.totalAmount afterPoint:2]];
            }
            
            [section1 addObject: footerTotalStr];
            [self.goodsDataSource addObject:section1];
        }
        self.formModel.order_goodsDataSource = self.goodsDataSource;

    }
    
    [_tableView reloadData];
}



#pragma mark delegate datasource
- (NSInteger)numberOfSectionsInGroupShadowTableView:(GroupShadowTableView *)tableView {
    return _sections.count;
}

- (NSInteger)groupShadowTableView:(GroupShadowTableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSMutableArray *sec = _sections[section];
    return sec.count;
}

- (UITableViewCell *)groupShadowTableView:(GroupShadowTableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSMutableArray *sec = _sections[indexPath.section];
    GDFiterCellModel *fiterModel = sec[indexPath.row];
    
    UITableViewCell *cell = [_tableView mc_dequeueReusableCellWithClassType:fiterModel.cellKlass];
    fiterModel.fiterCellModelBlock((MCTableBaseCell *)cell, fiterModel, self.formModel, indexPath);
    
    return cell;
}

- (CGFloat)groupShadowTableView:(GroupShadowTableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSMutableArray *sec = _sections[indexPath.section];
    GDFiterCellModel *fiterModel = sec[indexPath.row];
    return  [tableView fd_heightForCellWithIdentifier: NSStringFromClass(fiterModel.cellKlass) cacheByIndexPath:indexPath configuration:^(MCTableBaseCell *cell) {
            fiterModel.fiterCellModelBlock((MCTableBaseCell *)cell, fiterModel, self.formModel, indexPath);
       }];
}

#pragma mark - UITableViewDelegate
- (CGFloat)groupShadowTableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    NSMutableArray *sec = _sections[section];
    GDFiterCellModel *fiterModel = sec.firstObject;
    
    if (fiterModel.cellType == GDFiterCellTypeOrderGoods) {
        return CGFLOAT_MIN;
    }
    return 15;
}

- (UIView *)groupShadowTableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *v = [[UIView alloc] init];
    v.backgroundColor = [UIColor clearColor];
    return v;
}

- (void)groupShadowTableView:(GroupShadowTableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
     NSMutableArray *sec = _sections[indexPath.section];
    GDFiterCellModel *fiterModel = sec[indexPath.row];
    if (fiterModel.cellType == GDFiterCellTypeOrderPay) {
        HEPaymentModel *payModel = self.formModel.order_payments[indexPath.row];
        self.formModel.order_payType = payModel.code;
        [self changeSelectPayType:indexPath.row];
    }else if (fiterModel.cellType == GDFiterCellTypeOrderDispatch) {
        ZFScanViewController * vc = [[ZFScanViewController alloc] init];
        vc.returnScanBarCodeValue = ^(NSString * barCodeString){
            if ([barCodeString containsString:CODE_HG]) {
                self.formModel.order_staffId = [barCodeString substringFromIndex:CODE_HG.length];
                [self loadUserInfo];
            }
        };
        
         [self.navigationController pushViewController:vc animated:YES];
    }else if (fiterModel.cellType == GDFiterCellTypeOrderAddAddress) {
        [self selectAddressWithCell];
    }
}

- (void)loadUserInfo {
    [WOAFNetWorkingHandle POSTWithBaseUrlByKeyValue:KServerUrl suffixUrl:KgetUserInfo parameters:@{@"usid": self.formModel.order_staffId} success:^(id  _Nonnull responseObject) {
        HEResponse *response = [HEResponse mj_objectWithKeyValues:responseObject];
        UserInfo *user = [UserInfo mj_objectWithKeyValues:response.data];
        self.formModel.order_staffName = user.realname;
        [self.tableView reloadData];
    } failure:^(NSError * _Nonnull error) {
        
    }];
}

- (void)changeSelectPayType:(NSInteger)index {
    
    for (int i = 0; i < self.formModel.order_payments.count; i++) {
        HEPaymentModel *payModel = self.formModel.order_payments[i];
        if (index == i) {
            payModel.isChoose = YES;
        }else {
            payModel.isChoose = NO;
        }
    }
    
    [_tableView reloadData];
}


#pragma mark - HEOrderAddressCellDelegate
- (void)selectAddressWithCell {
    HEAddressViewController *vc = [HEAddressViewController new];
    vc.type = HEAddressIntoTypeToSelect;
    [vc selectAddress:^(HEReceiveAddressModel * _Nonnull model) {
        self.formModel.order_addres = model;
         
        __weak typeof(self) weakself = self;

        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        dispatch_async(queue, ^{
            weakself.group = dispatch_group_create();
            [weakself loadTranpFeeData];

            //因上面请求中有加入dispatch_group_enter 和 dispatch_group_leave,所以真正等待上面线程执行完才执行这里面的请求
            dispatch_group_notify(weakself.group, queue, ^{
                dispatch_main_async_safe(^{
                    [weakself initCell2];
                })
            });
        });
    }];
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - HEOrderTabBarViewDelegate
- (void)submitOrderHandler {
    
    if (![self toVaildRealUser]) {
        return;
    }
    
    if (self.formModel.order_addres == nil ) {
        [Dialog toast:@"请添加上门服务地址~" delay:2.0];
        return;
    }
    
    if (self.detials.cartPromotionItemList.count > 0) {
        HECartpromotionItemModel *carItem = self.detials.cartPromotionItemList.firstObject;
        if (carItem.channel == HEChannelTypeSpinalReh ||
            self.goods.visit) {
            if (![self.formModel.order_serverTime isNotBlank]) {
                [Dialog toastBottom:@"请选择服务时间~"];
                return;
            }
        }
    }
    
    if (self.formModel.order_payType == nil) {
        [Dialog toast:@"请选择支付方式~" delay:2.0];
        return;
    }

    
    [self crateOrder];
}

- (BOOL)toVaildRealUser {
    if (![[UserManager sharedUserManager] getUserInfo].verifyStatus) {
        HERealNameAuthAlterController *vc = [HERealNameAuthAlterController new];
        [self.view addSubview:vc.view];
        return NO;
     }
    return YES;
}

- (void)crateOrder {
    
    HECreateOrderRequest *request = [HECreateOrderRequest new];
    request.orderType = HEOrderTypeGeneral;
    request.content = self.formModel.order_leaveMsg;
    request.source = HEOrderSourceTypeiOS;
    request.addressId = self.formModel.order_addres.id;
    request.appSource = KAppSource;
    request.type = _previewType;

    if (self.previewType == HESubmitPreviewTypeByGoodsDetails) {
        request.total = 0;

        NSMutableArray *idArrs = [NSMutableArray array];
        for (HECartpromotionItemModel *goodItem in self.detials.cartPromotionItemList) {
            [idArrs addObject:[NSNumber numberWithInteger:goodItem.productId]];
            request.total += goodItem.quantity;
            request.channel = goodItem.channel;
            request.skuId = goodItem.productSkuId;
        }
        request.goodsId = [idArrs componentsJoinedByString:@","];
        
    }else {
        request.cartIds = _previewModel.cartIds;
    }
    
    if (self.detials.cartPromotionItemList.count > 0) {
        HECartpromotionItemModel *carItem = self.detials.cartPromotionItemList.firstObject;
        if (carItem.channel == HEChannelTypeSpinalReh) {
            request.serviceTime = self.formModel.order_serverTime;
        }else if (self.goods.visit) {
            request.serviceTime = self.formModel.order_serverTime;
            request.staffId = self.formModel.order_staffId;
            request.staffName = self.formModel.order_staffName;
        }
    }
        
    
    NSString *urls = @"";
    if (_previewType == HESubmitPreviewTypeByGoodsDetails) {
       urls = KgenerateOrder;
    }else if (_previewType == HESubmitPreviewTypeByCart) {
        urls = KgenerateStoreOrder;
    }

    [WOAFNetWorkingHandle POSTWithBaseUrlByKeyValue:KServerUrl suffixUrl:urls parameters:request success:^(id  _Nonnull responseObject) {
        NSLog(@"response：  %@", [responseObject mj_JSONString]);

        HEResponse *response = [HEResponse mj_objectWithKeyValues:responseObject];
        if (response.success) {
            HECreateOrderResponse *data = [HECreateOrderResponse mj_objectWithKeyValues:response.data];
            self.order = data.order;
            
            [HEPayManager sharedManager].order = data.order;
            
            // 发起支付
            if ([self.formModel.order_payType isEqualToString:KWxPayCode]) {
                [self createWxPayRequest:data.order.id];
            }else if ([self.formModel.order_payType isEqualToString:KAliPayCode]) {
                [self createAliPayRequest:data.order.id];
            }else if ([self.formModel.order_payType isEqualToString:KQRPayCode]) {
                [self showQRPay];
            }
        }
    } failure:^(NSError * _Nonnull error) {
        
    }];
}

#pragma mark 二维码支付
- (void)showQRPay {
    NSString *token = [[UserManager sharedUserManager] getToken];
    KWeakSelf
    [HEQRPayView showWithURL: [NSString stringWithFormat:@"https://www.honglutec.com/oldPay/codePage.html?appSource=%d&orderId=%ld&payPlatform=%@&token=%@&providerPay=%d", KAppSource, self.order.id, KPayPlatform, token, _order.storeId == 1 ? 0 : 1] cancelBlock:^{
        [weakSelf payFialure];
    }];
}

#pragma mark 请求支付宝支付串
- (void)createAliPayRequest:(NSInteger)orderId {
    NSMutableDictionary *dict = @{}.mutableCopy;
    [dict setValue:[NSNumber numberWithInteger:orderId] forKey: @"orderId"];
    [dict setValue:@(KAppSource) forKey: @"appSource"];
    [dict setValue:KPayPlatform forKey: @"payPlatform"];
    NSString *url = _order.storeId == 1 ? KAliAppPay : KAliAppProPay;
    [WOAFNetWorkingHandle POSTWithBaseUrlByKeyValue:KServerUrl suffixUrl:url parameters:dict success:^(id  _Nonnull responseObject) {
        NSLog(@"response：  %@", [responseObject mj_JSONString]);

        HEObjectDataResponse *response = [HEObjectDataResponse mj_objectWithKeyValues:responseObject];
        if (response.success) {
            [[HEPayManager sharedManager] senAliPayRequest:response.data];
        }
    } failure:^(NSError * _Nonnull error) {
        
    }];
}
#pragma mark 请求微信支付串
- (void)createWxPayRequest:(NSInteger)orderId {
    NSMutableDictionary *dict = @{}.mutableCopy;
    [dict setValue:[NSNumber numberWithInteger:orderId] forKey: @"orderId"];
    [dict setValue:@(KAppSource) forKey: @"appSource"];
    [dict setValue:KPayPlatform forKey: @"payPlatform"];
    NSString *url = _order.storeId == 1 ? KWxAppPay : KWxAppProPay;
    [WOAFNetWorkingHandle POSTWithBaseUrlByKeyValue:KServerUrl suffixUrl:url parameters:dict success:^(id  _Nonnull responseObject) {
        NSLog(@"response：  %@", [responseObject mj_JSONString]);

        HEObjectDataResponse *response = [HEObjectDataResponse mj_objectWithKeyValues:responseObject];
        HEWxPayReqModel *wxModel = [HEWxPayReqModel mj_objectWithKeyValues:[DYTools getContainersObjectFromJsonString:response.data]];
            
        PayReq* req = [[PayReq alloc] init];
        req.partnerId = wxModel.partnerid;
        req.prepayId = wxModel.prepayid;
        req.nonceStr = wxModel.noncestr;
        req.timeStamp = wxModel.timestamp.unsignedIntValue;
        req.package = wxModel.package;
        req.sign = wxModel.sign;
        [WXApi sendReq:req completion:^(BOOL success) {
            if (!success) {
                [Dialog toastBottom:@"支付失败~"];
                [self payFialure];
            }
        }];

    } failure:^(NSError * _Nonnull error) {
        
    }];
}


#pragma mark - 支付回调
- (void)paySuccess {
        
    // 支付成功，删除订单预览页，跳转到订单详请页
     HEPayResultResViewController *vc = [HEPayResultResViewController new];
      // 删除当前页
     [self.navigationController qmui_pushViewController:vc animated:YES completion:^{
      NSMutableArray *marr = [[NSMutableArray alloc]initWithArray:self.navigationController.viewControllers];
      for (UIViewController *vc in marr) {
          if ([vc isKindOfClass:[HECreateOrderViewController class]]) {
              [marr removeObject:vc];
              break;
          }
      }
      self.navigationController.viewControllers = marr;
     }];
}

- (void)payFialure {

    // 放弃支付或者支付失败，删除订单预览页，跳转到订单详请页
    HEOrderDetailsViewController *vc = [HEOrderDetailsViewController new];
    vc.orderId = self.order.id;
     // 删除当前页
    [self.navigationController qmui_pushViewController:vc animated:YES completion:^{
     NSMutableArray *marr = [[NSMutableArray alloc]initWithArray:self.navigationController.viewControllers];
     for (UIViewController *vc in marr) {
         if ([vc isKindOfClass:[HECreateOrderViewController class]]) {
             [marr removeObject:vc];
             break;
         }
     }
     self.navigationController.viewControllers = marr;
    }];
}
 

@end
